import { dailyPatients, _getPatientInfo } from '@/api/patientInfo'
import { getChecked } from '@/api/external'

const patient = {
  state: {
    patientInfo: null,
    visitNumToday: 0,
    dailyPatients: []
  },

  mutations: {
    SET_PATIENT_INFO: (state, patientInfo) => {
      state.patientInfo = patientInfo
    },
    SET_VISIT_NUM_TODAY: (state, visitNumToday) => {
      state.visitNumToday = visitNumToday
    },
    SET_DAILY_PATIENTS: (state, dailyPatients) => {
      state.dailyPatients = dailyPatients
    }
  },

  actions: {
    getPatientInfo({ commit, state }, patientId) {
      return new Promise((resolve, reject) => {
        if (!state.patientInfo || state.patientInfo.patientId !== patientId) {
          Promise.all([_getPatientInfo(patientId), getChecked(patientId)]).then(values =>{
            if (values[0].data) {
              const age = new Date().getFullYear() - parseInt(values[0].data.birthday.substr(0, 4))
              values[0].data.age = age
            }
            values[0].data.checked  = []
            let checkedIndex = {}
            values[1].data.forEach(e => {
              if (checkedIndex[e.itemClass] == undefined) {
                checkedIndex[e.itemClass] = values[0].data.checked.length
                values[0].data.checked.push({
                  name: e.itemClass,
                  dateTime: e.insertTime,
                  data: []
                })
              }
              values[0].data.checked[checkedIndex[e.itemClass]].data.push({
                itemCode: e.itemCode,
                itemName: e.itemName,
                resultValue: parseFloat(e.resultValue),
                startRange: parseFloat(e.startRange),
                endRange: parseFloat(e.endRange),
                resultUnit: e.resultUnit
              })
            })
            commit('SET_PATIENT_INFO', values[0].data)
            // localStorage.setItem('patientInfo', JSON.stringify(res.data))
            resolve(values[0].data)  
          }).catch(err => {
            reject(err)
          })
        } else {
          resolve(state.patientInfo)
        }
      })
    },
    getTodayPatients({ commit, state }, forceFlag) {
      return new Promise((resolve, reject) => {
        if (state.dailyPatients.length == 0 || forceFlag) {
          dailyPatients('2019-04-02').then(res => {
            commit('SET_DAILY_PATIENTS', res.data)
            commit('SET_VISIT_NUM_TODAY', res.data.length)
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
        } else {
          resolve(state.dailyPatients)
        }
      })
    }
  }
}

export default patient
